package com.syl.ippool.utils;

import com.syl.ippool.domain.IpBasePojo;
import com.syl.ippool.ifice.pool.IGraspIpPool;
import com.syl.ippool.threadtoos.MeThreadPool;
import com.syl.ippool.threadtoos.runs.CheckIpRunnable;

import java.io.IOException;
import java.net.*;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Future;

/**
 * 关于ip操作的工具类
 */
public class IpUtils {

    /**
     * 检测ip是否有效，如无效的删除
     *
     * @param ipBasePojoList 获得的新ip
     * @param graspIpPool    ip池
     */
    public static void checkActive(List<IpBasePojo> ipBasePojoList, IGraspIpPool graspIpPool) {
        int startThreadNum = 10;

        ArrayList<IpBasePojo> taskList = new ArrayList<>();

        for (int i = 0; i < ipBasePojoList.size(); i++) {

            taskList.add(ipBasePojoList.get(i));

            if ((taskList.size() >= startThreadNum) || (i == ipBasePojoList.size() - 1)) {
                MeThreadPool.fixedPool.execute(new CheckIpRunnable(ipBasePojoList,graspIpPool));
                ipBasePojoList = new ArrayList<>();
            }
        }

    }


    /**
     * 检测ip是否有效的方法
     *
     * @param ipBean
     * @return
     */
    public static boolean isValid(IpBasePojo ipBean) {
        Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(ipBean.getIp(), ipBean.getPort()));
        try {
            URLConnection httpCon = new URL("https://www.baidu.com/").openConnection(proxy);
            httpCon.setConnectTimeout(1000 * 10);
            httpCon.setReadTimeout(1000 * 10);
            int code = ((HttpURLConnection) httpCon).getResponseCode();
            return code == 200;
        } catch (IOException e) {
//            e.printStackTrace();
        }
        return false;
    }

}
